package cn.yeziji.forum.dao.impl;

import cn.yeziji.forum.converter.UserSettingsConverter;
import cn.yeziji.forum.dao.base.ForumUserSettingsBaseDao;
import cn.yeziji.forum.dao.intf.ForumUserDao;
import cn.yeziji.forum.dao.intf.ForumUserSettingsDao;
import cn.yeziji.forum.dao.iquery.UserSettingsQuery;
import cn.yeziji.forum.entity.ForumUserEntity;
import cn.yeziji.forum.entity.ForumUserSettingsEntity;
import cn.yeziji.forum.mapper.ForumUserSettingsMapper;
import cn.yeziji.forum.utils.JwtOperaUtils;
import cn.yeziji.forum.vo.settings.UserSettingsVO;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 用户配置表逻辑实现层
 *
 * @author gzkemays
 * @since 2022/04/07 10:01
 */
@Repository
public class ForumUserSettingsDaoImpl extends ForumUserSettingsBaseDao
    implements ForumUserSettingsDao {
  @Resource HttpServletRequest request;
  @Resource ForumUserSettingsMapper userSettingsMapper;
  @Resource ForumUserDao userDao;

  @Override
  public UserSettingsVO getUserSettings() {
    Integer userId = JwtOperaUtils.getUserIdByRequest(request);
    return getUserSettingsByUserId(userId);
  }

  @Override
  public UserSettingsVO getUserSettingsByNickname(String nickname) {
    ForumUserEntity userEntity = userDao.selectUserByNickName(nickname);
    return getUserSettingsByUserId(userEntity.getId());
  }

  /**
   * 根据用户 id 获取用户配置
   *
   * @param userId 用户id
   * @return 用户配置返回对象
   */
  private UserSettingsVO getUserSettingsByUserId(Integer userId) {
    ForumUserSettingsEntity one =
        userSettingsMapper.findOne(UserSettingsQuery.getUserSettingsByUserIdQuery(userId));
    // 用户没有配置，则设置默认配置
    if (one == null) {
      one = new ForumUserSettingsEntity();
      one.setUserId(userId);
      userSettingsMapper.insert(one);
      return UserSettingsVO.defaultSettings();
    }
    return UserSettingsConverter.INSTANCE.entityConverterToSettingsVo(one);
  }
}
